#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os.path
import argparse

from file_util import mkdir
from arkcompiler_tool import compile_file, gen_pa
from gen_arktsconfig import gen_arktsconfig


def compile_source_files(args, input_dir, output_dir, abc_files):
    mkdir(output_dir)
    for file in os.listdir(input_dir):
        input_file_path = os.path.join(input_dir, file)
        if os.path.isdir(input_file_path):
            compile_source_files(args, input_file_path, os.path.join(output_dir, file), abc_files)
        else:
            if not file.endswith('ets'):
                continue
            abc_file_path = os.path.join(output_dir, file.replace('.ets', '.abc'))
            pa_file_path = os.path.join(output_dir, file.replace('.ets', '.pa'))
            print('input_file:{}'.format(input_file_path))
            print('abc_file:{}'.format(abc_file_path))
            print('pa_file_path:{}'.format(pa_file_path))
            abc_files.append(abc_file_path)

            compile_file(args.arkcompiler_cmd_tool_path, args.tmp_arktsconfig_file, input_file_path, abc_file_path)
            gen_pa(args.arkcompiler_cmd_tool_path, abc_file_path, pa_file_path)


def compile_source():
    parser = argparse.ArgumentParser()
    parser.add_argument('--arkcompiler_tool_path', help='arkcompiler tool path')
    parser.add_argument('--arktsconfig_file', help='arktsconfig template file')
    parser.add_argument('--src_root', help='source ets file root path')
    parser.add_argument('--build_root', help='build dir root path')

    args = parser.parse_args()
    args.tmp_arktsconfig_file = os.path.join(args.build_root, 'arktsconfig.json')
    args.arkcompiler_cmd_tool_path = os.path.join(args.arkcompiler_tool_path, 'clang_x64')
    args.ets_plugins_path = os.path.join(args.arkcompiler_tool_path, 'plugins', 'ets', 'stdlib')

    print('arkcompiler_tool_path:{}'.format(args.arkcompiler_tool_path))
    print('arktsconfig_file:{}'.format(args.arktsconfig_file))
    print('src_root:{}'.format(args.src_root))
    print('build_root:{}'.format(args.build_root))

    print('compile...')
    gen_arktsconfig(args.build_root, args.src_root, args.ets_plugins_path, args.arktsconfig_file, args.tmp_arktsconfig_file)
    abc_files = []
    compile_source_files(args, args.src_root, args.build_root, abc_files)


if __name__ == '__main__':
    compile_source()
